import {memoizedThsNews} from "@/backend/services/ths-service";
import {getRisk} from "@/backend/services/secu-service";
import {format} from "date-fns";
import styles from "./page.module.scss"

type thsNews = {
    newsId: string,
    newsTitle: string,
    newsTime: string,
    newsUrl: string,
    newsTimeObj: Date
}


export default async function NewsPage({params, searchParams}: {
    params: Promise<{ code: string }>,
    searchParams: Promise<any>
}) {
    const {code} = await params;
    if (!code) return null
    const zdjk = await getRisk(code)
    const cachedNews: thsNews[] = await memoizedThsNews(code);
    let thsNews = structuredClone(cachedNews)
    const now = new Date();
    thsNews = thsNews.filter(n => {
        const diffDays = Math.ceil((now.getTime() - n.newsTimeObj.getTime()) / 1000 / 60 / 60 / 24)
        return diffDays <= 7;
    });

    const riskNews: thsNews[] = thsNews.filter(t => {
        if (t.newsTitle.toLowerCase().includes('风险提示')) {
            t.newsTitle = `💀💀💀💀💀` + t.newsTitle
            return true
        }
        return false
    })
    const todayStr = format(new Date(), 'MM-dd');
    const {split} = await searchParams;
    // 只挑选非10jqka的文章
    let otherNews: thsNews[] = []
    if (split === '1') {
        otherNews = thsNews.filter(n => !n.newsUrl.includes("10jqka"))
        thsNews = thsNews.filter(n => n.newsUrl.includes("10jqka"))
    }
    return <div className={styles.newsContainer}>

        {riskNews.length > 0 || zdjk !== null ?
            <>
                <p className={`${styles.riskPrompt}`}>禁止买入</p>
                <hr className={`p-0 m-0`}/>
            </>
            : null
        }
        {
            otherNews.map((n) => (
                    <p key={n.newsUrl}
                       className={`${styles.newsItem} ${!n.newsUrl.includes("10jqka") ? styles.noThsNewsColor : n.newsTime.includes(todayStr) ? styles.todayNewsColor : ""}`}
                    >
                        <a href={n.newsUrl} target="_blank"> {n.newsTime} | {n.newsTitle}</a>
                    </p>
                )
            )
        }

        {
            thsNews.map((n, i) => (
                    <p key={i}
                       className={`${styles.newsItem} ${!n.newsUrl.includes("10jqka") ? styles.noThsNewsColor : n.newsTime.includes(todayStr) ? styles.todayNewsColor : ""}`}
                    >
                        <a href={n.newsUrl} target="_blank"> {n.newsTime} | {n.newsTitle}</a>
                    </p>
                )
            )
        }

    </div>
}